package com.zlt.service.impl;

import com.alipay.api.domain.CompanyInfo;
import com.zlt.dao.CompanyDao;
import com.zlt.dao.Impl.CompanyDaoImpl;
import com.zlt.dao.Impl.OfferDaoImpl;
import com.zlt.dao.Impl.UserDaoImpl;
import com.zlt.dao.OfferDao;
import com.zlt.dao.UserDao;
import com.zlt.dto.OfferDto;
import com.zlt.entity.Company;
import com.zlt.entity.Offer;
import com.zlt.entity.ReOffer;
import com.zlt.entity.User;
import com.zlt.service.OfferService;
import com.zlt.util.*;
import com.zlt.vo.ActiveUser;
import com.zlt.vo.OfferVo;
import com.zlt.vo.Pager;
import com.zlt.vo.ReOfferVo;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.Part;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class OfferServiceImpl implements OfferService {

    //创建offer dao层对象
    private OfferDao offerDao=new OfferDaoImpl();

    //创建company dao层对象
    private CompanyDao companyDao=new CompanyDaoImpl();

    //创建user dao层对象
    private UserDao userDao=new UserDaoImpl();

    /**
     * offer暂存
     * @param email
     * @param phone
     * @param validTime
     * @param content
     * @return
     */
    public  boolean addOffer(String email, String phone, String validTime, String content, Part offerFile) {
        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录,请登录");
        }
        Company companyInfo=companyDao.selectCompanyInfoByUid(activeUser.getUid(),0,0);
        if(companyInfo==null){
            throw new RuntimeException("offer添加失败");
        }
        String url=null;
        if(offerFile!=null){
            //上传了文件
            if(offerFile.getSize()>0){
                String submittedFileName = offerFile.getSubmittedFileName();
                String fileName= UUID.randomUUID()+submittedFileName.substring(submittedFileName.lastIndexOf("."));
                String savePath="D:\\JavaPractice\\files"+File.separator;
                try {
                    offerFile.write(savePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //访问路径
                url = "http://localhost:8080//files" + File.separator+fileName;

            }

        }


        User user=userDao.selectUserByUsername(phone);
        if(user==null){
            throw new RuntimeException("offer添加失败，手机号错误");
        }

        Offer offer=new Offer(null,null,  1,validTime,companyInfo,user,content,null,url);
        return offerDao.insertOffer(offer)>0;
    }


    @Override
    public boolean sendOffer(OfferDto offerDto)  {

        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录,请登录");
        }
        //测试使用====================
        String uid="1";
        //===================

        StringBuilder builder=new StringBuilder();
        if(offerDto==null){
            throw new RuntimeException("数据异常，发送失败");
        }

        Integer state = offerDto.getState();
        switch (state){
            case 0: throw new RuntimeException("offer已发送");
            case 2:throw new RuntimeException("offer已接收");
            case 3:throw new RuntimeException("offer已拒绝");
            case 4:throw new RuntimeException("offer已删除");
        }

        //发送给求职者的邮箱
        String email = offerDto.getEmail();

        String content = offerDto.getContent();
        String cname = offerDto.getCname();
        String sendTime = offerDto.getSendTime();
        String validTime = offerDto.getValidTime();
        String username = offerDto.getUsername();

        builder.append(cname+" 欢迎 "+username+" 的加入!");
        builder.append("\r\n");
        builder.append("offer具体描述如下：");
        builder.append("\r\n");
        builder.append(content);
        builder.append("\r\n");
        builder.append("offer截止时间："+validTime);

        //通过邮箱发送offer给求职者==================
        boolean b = EmailUtil.sendEmail(email, "你有一份来自 " + cname + " 的offer "+offerDto.getSubject(), builder.toString());
        offerDto.setSendTime(StringUtil.getCurrentTime());
        if(b){
            //修改offer状态
            boolean isSuccess=offerDao.updateOfferState(offerDto.getOid(),0)>0;
            //修改offer的发送时间
            boolean b1 = updateOffer(offerDto);
        }
        //========================================

        //通过短信发送offer给求职者===================

        //=========================================
        return b;
    }

    @Override
    public boolean deleteOffer(List<OfferVo> offerVoList) {
        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录,请登录");
        }

        if(offerVoList==null){
            throw  new RuntimeException("数据异常，操作失败");
        }
        boolean isSuccess=false;
        for (OfferVo offerVo : offerVoList) {
            if(offerVo.getState()==4){
                throw new RuntimeException("offer已删除");
            }
            isSuccess =offerDao.updateOfferState(offerVo.getOid(),4)>0;
        }
        return isSuccess;
    }

    /**
     * 更新offer内容
     * @param offerDto
     * @return
     */
    @Override
    public boolean updateOffer(OfferDto offerDto) {
        //OfferDto(oid=2, sendTime=null, state=null, validTime=2022-08-11 09:09:07.0,
        // cname=null, username=15775773164,
        // content=月薪20万, note=null, url=null, email=3148529981@qq.com)
        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录,请登录");
        }
        if(offerDto==null){
            throw  new RuntimeException("数据异常，操作失败");
        }

        StringBuilder autoSql=new StringBuilder();
        List<Object> params=new ArrayList<>();
        autoSql.append("update offer set ");
        if(offerDto.getValidTime()!=null){
           autoSql.append(" valid_time=?, ");
           params.add(offerDto.getValidTime());
        }
        if(offerDto.getContent()!=null){
            autoSql.append(" content=?, ");
            params.add(offerDto.getContent());
        }

        if(offerDto.getSendTime()!=null){
            autoSql.append(" send_time=?, ");
            params.add(offerDto.getSendTime());
        }

        autoSql.append(" where oid=?");
        params.add(offerDto.getOid());
        autoSql.delete(autoSql.lastIndexOf(","),autoSql.lastIndexOf(",")+1);

        return offerDao.updateOffer(autoSql.toString(),params.toArray())>0;
    }


    /**
     * 通过邮箱发送offer
     * @param url
     * @param jsUid
     * @param validTime
     * @return
     */
    public boolean sendOffer(String url, String jsUid,String validTime) {
        ActiveUser activeUser = ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录，请登录");
        }

        //当前招聘者的uid
        String uid = activeUser.getUid();
        //招聘者
        User recruite = userDao.selectUserByUid(uid);
        //招聘者所在公司
        Company companyInfo=companyDao.selectCompanyInfoByUid(uid,0,0);
        if(companyInfo==null){
            throw new RuntimeException("数据异常,offer添加失败");
        }
        //求职者
        User jbsk = userDao.selectUserByUid(jsUid);
        if(recruite==null || jsUid==null){
            throw new RuntimeException("数据异常,offer添加失败");
        }
        String email = jbsk.getEmail();
        if(!StringUtil.isNotNull(email)){
            throw new RuntimeException("求职者邮箱为空，offer发送错误");
        }

        Offer offer=new Offer(null,StringUtil.getCurrentTime(),  1,validTime,companyInfo,jbsk,null,null,url);
        boolean saveOfferResult = offerDao.insertOffer(offer)>0;
        boolean sendResult=false;
        if(saveOfferResult){
             sendResult = EmailUtil.sendEmail(email, "欢迎：" + jbsk.getUsername() + " 加入！", "详情请参看offer");
             //如果offer发送成功，修改offer的发送时间
        }
        return sendResult;

    }

    /**
     * 查询对应公司所有offer
     * @param pager
     * @return
     */
    public Pager<OfferVo> selectAllOffer(Pager<OfferVo> pager) {
        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前用户未登录,请先登录");
        }
        String uid = activeUser.getUid();

        Company companyInfo = companyDao.selectCompanyInfoByUid(uid,0,0);
        System.out.println(companyInfo.toString());
        if(companyInfo==null){
            throw new RuntimeException("数据异常,请重试");
        }


        Long totalCount=offerDao.selectOfferCountByCid(companyInfo.getCid());
        pager.setTotalCount(totalCount);

        pager.setPageCount((totalCount-1)/ pager.getLimit()+1);

        List<Offer> offerList=new ArrayList<>();
        List<OfferVo> offerVoList=new ArrayList<>();
        offerList=offerDao.selectAllOffer(pager.getPage(),pager.getLimit(),companyInfo.getCid());
        for (Offer offer : offerList) {
            OfferVo offerVo=new OfferVo();
            offerVoList.add(offerVo);
            offerVo.setCname(offer.getCompanyInfo().getCname());
            offerVo.setUsername((null==offer.getUser().getUsername())?offer.getUser().getEmail():offer.getUser().getUsername());
            User user = userDao.selectUserByUid(offer.getUser().getUid());
            if(user!=null){
                offerVo.setEmail(user.getEmail());
            }

            try {
                BeanUtils.copyProperties(offerVo,offer);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        pager.setData(offerVoList);
        for (OfferVo datum : pager.getData()) {
            System.out.println(datum.toString());
        }
        return pager;
    }

    @Override
    public boolean chickOffer(String token,String oid, String chick) {
        String username = JWTUtil.getUsername(token);
        String s = null;
        if ("confirm".equals(chick)){
            s = "2";
        }
        else if("refuse".equals(chick)){
            s = "3";
        }
        return offerDao.chickOffer(username,oid,s)>0?true:false;
    }

    @Override
    public List<ReOfferVo> showOffer(String token) {
        String username = JWTUtil.getUsername(token);
        List<ReOffer> list = offerDao.show(username);
        List<ReOfferVo> reOfferVos = new ArrayList<>();
        System.out.println(list);
        for (ReOffer reOffer : list){
            reOfferVos.add(
                    new ReOfferVo(
                            reOffer.getOid(),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(reOffer.getSendTime().getTime()),
                            reOffer.getState(),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(reOffer.getValidTime().getTime()),
                            reOffer.getCompany(),
                            reOffer.getNote(),
                            reOffer.getContent()
                    )
            );
        }
        return reOfferVos;
    }

    @Override
    public boolean addOfflineOffer(OfferDto offerDto, String url) {
        ActiveUser activeUser=ActiveUserUtil.get();
        if(activeUser==null){
            throw new RuntimeException("当前未登录,请登录");
        }
        Company companyInfo=companyDao.selectCompanyInfoByUid(activeUser.getUid(),0,0);
        if(companyInfo==null){
            throw new RuntimeException("offer添加失败");
        }

        User user = userDao.selectUserByUsername(offerDto.getUsername());
        Offer offer=new Offer(null,StringUtil.getCurrentTime(),  0,null,companyInfo,user,offerDto.getSubject()+offerDto.getContent(),null,url);
        return offerDao.insertOffer(offer)>0;
    }

}

